/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.admin.security.listener;

import vip.dexian.admin.dto.AdminPrincipal;
import vip.dexian.admin.entity.LoginLog;
import vip.dexian.admin.service.LoginLogService;
import vip.dexian.common.utils.IpToLongUtils;
import vip.dexian.common.utils.UserAgentUtils;
import vip.dexian.common.utils.WebUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * 登录成功监听
 *
 * @author 挺好的 2023年06月06日 16:38
 */
@Slf4j
@Component
public class AuthenticationSuccessListener implements ApplicationListener <AuthenticationSuccessEvent> {

    /**
     * 管理员登录日志
     */
    @Resource (name = "loginLogServiceImpl")
    private LoginLogService adminLoginLogService;

    @Override
    public void onApplicationEvent (AuthenticationSuccessEvent event) {

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(
                RequestContextHolder.getRequestAttributes())).getRequest();

        AdminPrincipal adminPrincipal = (AdminPrincipal) event.getAuthentication().getPrincipal();

        UserAgentUtils.UserAgentInfo userAgentInfo = UserAgentUtils.parse(request);

        LoginLog loginLog = LoginLog.builder().username(adminPrincipal.getUsername()).password(StringUtils.EMPTY)
                .isSuccess(true).memo("登录成功").ip(IpToLongUtils.toLong(WebUtils.getIPAddr(request)))
                .browser(userAgentInfo.getBrowser()).browserVersion(userAgentInfo.getBrowserVersion())
                .osName(userAgentInfo.getOsName()).deviceType(userAgentInfo.getDeviceType()).build();

        this.adminLoginLogService.login(loginLog);

    }
}
